"""FastAPI主应用文件"""
import logging
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
from sqlalchemy import text
from app.config.database import engine, Base
from app.routes.main_routes import api_router
from app.utils.redis_util import get_redis_util, redis_util

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时
    logger.info("应用启动中...")
    
    # 数据库连接检查（不再强制创建表）
    try:
        # 只测试数据库连接，不强制创建表
        with engine.connect() as conn:
            conn.execute(text("SELECT 1"))
            logger.info("数据库连接成功")
    except Exception as e:
        logger.error(f"数据库连接失败: {e}")
    
    # 重新初始化Redis工具并测试连接
    global redis_util
    try:
        # 强制重新初始化Redis工具
        redis_util = get_redis_util()
        if redis_util.test_connection():
            logger.info("Redis连接成功")
        else:
            logger.warning("Redis连接测试失败")
    except Exception as e:
        logger.error(f"Redis连接失败: {e}")
    
    yield
    
    # 关闭时
    logger.info("应用关闭中...")


# 创建FastAPI应用实例
app = FastAPI(
    title="Bilibili 模仿项目 API",
    description="基于FastAPI开发的视频分享平台API",
    version="1.0.0",
    lifespan=lifespan
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 在生产环境中应该设置具体的域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(api_router)


@app.get("/")
def root():
    """根路径"""
    return {
        "message": "Welcome to Bilibili API",
        "version": "1.0.0",
        "docs": "/docs"
    }


@app.get("/health")
def health_check():
    """健康检查"""
    return {"status": "healthy"}


if __name__ == "__main__":
    import uvicorn
    uvicorn.run("app.main:app", host="0.0.0.0", port=8000, reload=True)
